package com.gobo.jinghuimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.gobo.common.constant.ProductConstant;
import com.gobo.common.es.SkuEsModel;
import com.gobo.common.to.SkuReductionTo;
import com.gobo.common.to.SpuBoundsTo;
import com.gobo.common.utils.R;
import com.gobo.common.vo.SkuHasStockVo;
import com.gobo.jinghuimall.product.dao.AttrDao;
import com.gobo.jinghuimall.product.entity.*;
import com.gobo.jinghuimall.product.feign.CouponFeign;
import com.gobo.jinghuimall.product.feign.EsFegin;
import com.gobo.jinghuimall.product.feign.WareFegin;
import com.gobo.jinghuimall.product.service.*;
import com.gobo.jinghuimall.product.vo.*;
import org.bouncycastle.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gobo.common.utils.PageUtils;
import com.gobo.common.utils.Query;

import com.gobo.jinghuimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeign couponFeign;

    @Autowired
    private AttrService attrService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFegin wareFegin;

    @Autowired
    private EsFegin esFegin;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品
     *
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuSaveVo(SpuSaveVo spuSaveVo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();
        //2、保存Spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", spuSaveVo.getDecript()));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        //3、保存spu的图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveSpuImages(spuId, images);
        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(obj -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(obj.getAttrId());
            AttrEntity attrEntity = attrDao.selectById(obj.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(obj.getAttrValues());
            productAttrValueEntity.setQuickShow(obj.getShowDesc());
            productAttrValueEntity.setSpuId(spuId);
            productAttrValueEntity.setAttrSort(1);
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
        //5、保存spu的积分信息；jinghuimall_sms->sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);
        System.out.println("没有问题-》  5  ");
        R r = couponFeign.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu优惠信息失败！");
        }

        //5、保存当前spu对应的所有sku信息；
        //5.1）、sku的基本信息；pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(obj -> {
                String defaultImg = "";
                for (Images image : obj.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(obj, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                //图片返回true就是需要，false就是剔除
                //5.2）、sku的图片信息；pms_sku_image
                List<Images> objImages = obj.getImages();
                List<SkuImagesEntity> imagesEntities = objImages.stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回true就是需要，false就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value

                List<Attr> attr = obj.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(o -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    skuSaleAttrValueEntity.setAttrName(o.getAttrName());
                    skuSaleAttrValueEntity.setAttrValue(o.getAttrValue());
                    skuSaleAttrValueEntity.setAttrSort(1);
                    skuSaleAttrValueEntity.setAttrId(o.getAttrId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveSkuSaleAttrValueEntitys(skuSaleAttrValueEntities);

                //5.4）、sku的优惠、满减等信息；jinghuimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price

                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(obj, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeign.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }

    }

    @Override
    public PageUtils queryPageConditon(Map<String, Object> params) {
        /**
         * status: 0
         * key: 0
         * brandId: 4
         * catelogId: 225
         */
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status) && !"0".equals(status)) {
            queryWrapper.eq("publish_status", status);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(obj -> {
                obj.eq("id", key).or().like("spu_name", key).or().like("spu_description", key);
            });
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架服务
     * elasticSearch的部署
     * 仓库的容量
     *
     * @param spuId
     */
    @Transactional
    @Override
    public void spuUp(Long spuId) {
        //1、查出当前spuId对应的所有sku信息,品牌的名字
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.getSkusBySpuId(spuId);
        //查出当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListforspu(spuId);
        //将所有的baseAttrs的id收集出来，用来查询是否需要被检索
        List<Long> attrIds = baseAttrs.stream().map(o -> {
            return o.getAttrId();
        }).collect(Collectors.toList());
        List<Long> attrSearchIds = attrService.selectSearchAttrs(attrIds);
        //转换为Set集合
        Set<Long> idSet = attrSearchIds.stream().collect(Collectors.toSet());
        //收集所有的Attr
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());
        //收集所有SKU的Id
        List<Long> skuIdList = skuInfoEntityList.stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());
        Map<Long, Boolean> hashmap = null;
        // 1、发送远程调用，库存系统查询是否有库存
        try {
            R skuHasStock = wareFegin.getSkuHasStock(skuIdList);
            //
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            hashmap = skuHasStock.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("远程查询库存容量异常，{}", e);
        }

        //2、封装每个sku的信息
        Map<Long, Boolean> finalHashmap = hashmap;
        List<SkuEsModel> collect = skuInfoEntityList.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //设置库存信息
            Boolean aBoolean = (finalHashmap == null) ? true : finalHashmap.get(sku.getSkuId());
            if (aBoolean == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(aBoolean);
            }
            // 2、热度评分。0
            esModel.setHotScore(0L);

            // 3、查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandId(brandEntity.getBrandId());
            esModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogId(categoryEntity.getCatId());
            esModel.setCatalogName(categoryEntity.getName());

            //设置检索属性
            esModel.setAttrs(attrsList);

            BeanUtils.copyProperties(sku, esModel);

            return esModel;
        }).collect(Collectors.toList());
        //5、将数据发给es进行保存：jinghuimall-search
        R r = esFegin.productStatusUp(collect);

        if (r.getCode() == 0) {
            //远程调用成功
            //6、修改当前spu的状态
            this.baseMapper.updaSpuStatus(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
            //TODO  重复调用  (接口幂等性:重试机制)
        }

    }

}